import {UserActions} from './user';

const initialState = {
  total: 0,
  current: 1,
  pageSize: 10,
  results: {},
};

export const SearchResultActions = {
  SEARCH_RESULT_LIST_UPDATE: 'search_result_list_update',
  SEARCH_RESULT_LIST_REFRESH: 'search_result_list_refresh',
  SEARCH_RESULT_LIST_APPEND: 'search_result_list_append',
  SEARCH_RESULT_LIST_RESET: 'search_result_list_reset',
};

export function refreshSearchResultList(payload) {
  return {
    type: SearchResultActions.SEARCH_RESULT_LIST_REFRESH,
    payload,
  };
}

export function appendSearchResultList(payload) {
  return {
    type: SearchResultActions.SEARCH_RESULT_LIST_APPEND,
    payload,
  };
}

export function resetSearchResultList(payload) {
  return {
    type: SearchResultActions.SEARCH_RESULT_LIST_RESET,
    payload,
  };
}

export default function searchResultList(state = initialState, action) {
  const results = {};
  switch (action.type) {
    case SearchResultActions.SEARCH_RESULT_LIST_REFRESH:
      action.payload.results.forEach((item, index) => {
        results[item.id] = {...item, index};
      });
      return {
        ...action.payload,
        results: {...results},
      };
    case SearchResultActions.SEARCH_RESULT_LIST_APPEND:
      const values = Object.values(state.results);
      action.payload.results.forEach((item, index) => {
        results[item.id] = {...item, index: values.length + index};
      });
      return {
        ...action.payload,
        results: {...state.results, ...results},
      };
    case SearchResultActions.SEARCH_RESULT_LIST_RESET:
      return {
        total: 0,
        current: 1,
        pageSize: 10,
        results: {},
      };
    case UserActions.USER_SIGN_OUT:
      return {
        total: 0,
        current: 1,
        pageSize: 10,
        results: {},
      };
    default:
      return state;
  }
}
